package com.mdxl.controller;


import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chengjian on 2017/9/19.
 * https://www.netkiller.cn/java/elasticsearch/index.html
 */
@Controller
@RequestMapping(value = "/elasticsearch")
public class ESFirstController {
    private final static String article="article";
    private final static String content="content";
    @Autowired
    private TransportClient client;

    @RequestMapping(value = "/client/{articleId}",method =RequestMethod.GET)
    public GetResponse test(@PathVariable String articleId) {
        GetResponse response = client.prepareGet("information", "article", articleId).get();
        return response;
    }
    @RequestMapping(value = "/clien/aa",method = RequestMethod.GET)
    public void addIndexAndDocument() throws Exception{
        createData();
        Date time = new Date();
        IndexResponse response = client.prepareIndex("fendo", "es")
                .setSource(XContentFactory.jsonBuilder().startObject()
                        .field("id","447")
                        .field("author","fendo")
                        .field("title","192.138.1.2")
                        .field("content","这是JAVA有关的书籍")
                        .field("price","20")
                        .field("view","100")
                        .field("tag","a,b,c,d,e,f")
                        .field("date",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time))
                        .endObject())
                .get();
        System.out.println("添加索引成功,版本号："+response.getVersion());
    }
    public void CreateIndexAndMapping() throws Exception{

        CreateIndexRequestBuilder cib=client.admin().indices().prepareCreate(article);
        XContentBuilder mapping = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("properties") //设置之定义字段
                .startObject("author")
                .field("type","string") //设置数据类型
                .endObject()
                .startObject("title")
                .field("type","string")
                .endObject()
                .startObject("content")
                .field("type","string")
                .endObject()
                .startObject("price")
                .field("type","string")
                .endObject()
                .startObject("view")
                .field("type","string")
                .endObject()
                .startObject("tag")
                .field("type","string")
                .endObject()
                .startObject("date")
                .field("type","date")  //设置Date类型
                .field("format","yyyy-MM-dd HH:mm:ss") //设置Date的格式
                .endObject()
                .endObject()
                .endObject();
        cib.addMapping(content, mapping);

        CreateIndexResponse res=cib.execute().actionGet();

        System.out.println("----------添加映射成功----------");
    }
    public void createData() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "Neo Chen");
        map.put("age", 30);
        map.put("book", new String[]{"Netkiller Linux 手札","Netkiller Java 手札"});
        map.put("website", "http://www.netkiller.cn");
        map.put("email", "netkiller@msn.com");

        IndexResponse response = client.prepareIndex("fendo", "es", UUID.randomUUID().toString())
                .setSource(map).get();
        System.out.println("Status: " + response.status().getStatus() + "！id=" + response.getId());
    }
    @RequestMapping(value = "/article/{articleId}")
    public GetResponse read(@PathVariable String articleId) {
        GetResponse response = client.prepareGet("information", "article", articleId).get();
        return response;
    }
    @RequestMapping(value = "/article/delete/{articleId}")
    public void delete(@PathVariable("articleId")String articleId){
        DeleteResponse response = client.prepareDelete("book", "computer", "1")
                .get();

    }
    @RequestMapping(value = "/article/search/list")
    public List<Map<String, Object>> list() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        SearchResponse response = client.prepareSearch("information").setTypes("article")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).addSort("ctime", SortOrder.DESC)
                .setFrom(0).setSize(60).setExplain(true).get();
        for (final SearchHit hit : response.getHits().getHits()) {
            System.out.println(hit.getSourceAsString());
            hit.getSourceAsMap().remove("content");
            list.add(hit.getSourceAsMap());
        }
        return list;
    }
    //match 匹配查询
    public void match() {
        SearchRequestBuilder requestBuilder = client.prepareSearch("company").setTypes("employee")
                .setQuery(QueryBuilders.matchQuery("name", "neo"));
        System.out.println(requestBuilder.toString());

        SearchResponse response = requestBuilder.get();

        System.out.println(response.status());
        if (response.status().getStatus() == 200) {
            for (SearchHit hits : response.getHits().getHits()) {
                System.out.println(hits.getSourceAsString());
            }
        }
    }
    //match phrase 短语精准匹配
    public void matchPhrase() {
        SearchRequestBuilder requestBuilder = client.prepareSearch("company").setTypes("employee")
                .setQuery(QueryBuilders.matchPhraseQuery("name", "neo"));

        SearchResponse response = requestBuilder.get();

        if (response.status().getStatus() == 200) {
            for (SearchHit hits : response.getHits().getHits()) {
                System.out.println(hits.getSourceAsString());
            }
        }
    }
    //Filter term range
    public void filter(){
      /*  FilterBuilder filterBuilder = FilterBuilders.andFilter(
                FilterBuilders.existsFilter("title").filterName("exist"),
                FilterBuilders.termFilter("title", "elastic")
        );

        SearchResponse response = client.prepareSearch("netkiller")
                .setPostFilter(filterBuilder)
                .get();
*/
    }
    //sort
    public void sort(){
        SearchResponse response = client.prepareSearch("netkiller")
                .setQuery(QueryBuilders.matchAllQuery())
                .addSort(SortBuilders.fieldSort("title"))
                .addSort("_score", SortOrder.DESC)
                .get();
    }
}
